package edu.ccut.saturn.workflow.delegate;

import java.sql.Connection;
import java.util.ArrayList;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.operation.Operation;
import edu.ccut.saturn.workflow.common.Constants;

public class ExecuteHelp extends DefaultComponent{
	public void execute(IParameterContext parameterContext) throws Exception {
		String workitemId = (String)parameterContext.getParameterValue(0);
		String assistant = (String)parameterContext.getParameterValue(1);
		Connection conn = parameterContext.getConnection();
		String sql = "select * from wf_wiparticipant where workitemid="+workitemId
				   +" and participant='"+assistant+"' and partiintype='Y'";
		ArrayList<SaturnData> participantList = Operation.dataBase()
					.queryBySQL(Constants.SATURNDATA_WF_WIPARTICIPANT, sql, conn);
		if(participantList!=null){
			//删除其他协办者
			sql = "delete from wf_wiparticipant where participant!='"+assistant+"'"
				+" and workitemstate='"+Constants.WORKITEM_BIZSTATE_HELP+"'";
			Operation.dataBase().deleteBySQL(sql, conn);
			
			//设此工作项的其他参与者的partiintype='N'
			sql = "update wf_wiparticipant set partiintype='N' where workitemid="+workitemId;
			Operation.dataBase().updateBySQL(sql, conn);
			
			//查询代办表，得到委托人
			sql = "select * from wf_delegate where workitem_id="+workitemId+" and state='"+Constants.DELEGATE_STATE_RUNNING+"'";
			SaturnData delegateInst = Operation.dataBase()
								.queryBySQL(Constants.SATURNDATA_WF_DELEGATE, sql, conn).get(0);
			delegateInst.set("state", Constants.DELEGATE_STATE_FINISH);
			Operation.dataBase().updateByPrimaryKey(delegateInst, "", conn);
			//设置委托人的执行权限partiintype='Y'
			sql = "update wf_wiparticipant set partiintype='Y' where workitemid="+workitemId
				+" and participant= '"+delegateInst.get("delegate_from")+"'";
			Operation.dataBase().updateBySQL(sql, conn);
			
			//更新工作项状态为待确认
			SaturnData workitemInst = Operation.dataBase()
					.queryByPrimaryKey(Constants.SATURNDATA_WF_WORKITEM_INSTANCE, workitemId, conn);
			workitemInst.set("bizstate", Constants.WORKITEM_BIZSTATEHELP_WAITAFFIRM);
			Operation.dataBase().updateByPrimaryKey(workitemInst, "", conn);
		}else{
			throw new Exception("alreaday execute");
		}
	}

}
